package org.dromara.common.sse.listener

import cn.hutool.core.collection.CollUtil
import io.github.oshai.kotlinlogging.KotlinLogging
import org.dromara.common.sse.core.SseEmitterManager
import org.dromara.common.sse.dto.SseMessageDto
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.core.Ordered

/**
 * SSE 主题订阅监听器
 *
 * @author LikeYouDo
 * @date 2025/07/25
 */
class SseTopicListener : ApplicationRunner, Ordered {

    @Autowired
    private lateinit var sseEmitterManager: SseEmitterManager


    companion object {
        private val log = KotlinLogging.logger { }
    }

    /**
     * 在Spring Boot应用程序启动时初始化SSE主题订阅监听器
     *
     * @param args 应用程序参数
     * @throws Exception 初始化过程中可能抛出的异常
     */
    @Throws(Exception::class)
    override fun run(args: ApplicationArguments) {
        sseEmitterManager.subscribeMessage { message: SseMessageDto ->
            log.info {
                "SSE主题订阅收到消息session keys=${message.userIds} message=${message.message}"
            }
            // 如果key不为空就按照key发消息 如果为空就群发
            if (CollUtil.isNotEmpty(message.userIds)) {
                message.userIds?.forEach({ key: Long? ->
                    key?.let {
                        sseEmitterManager.sendMessage(key, message.message)
                    }
                })
            } else {
                sseEmitterManager.sendMessage(message.message)
            }
        }
        log.info { "初始化SSE主题订阅监听器成功" }
    }

    override fun getOrder(): Int {
        return -1
    }
}
